package link.chengguo.orangemall.controller.oms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.enums.*;
import link.chengguo.orangemall.oms.entity.OmsOrder;
import link.chengguo.orangemall.oms.entity.OmsOrderItem;
import link.chengguo.orangemall.oms.entity.OmsOrderOperateHistory;
import link.chengguo.orangemall.oms.mapper.OmsOrderOperateHistoryMapper;
import link.chengguo.orangemall.service.oms.IOmsOrderItemService;
import link.chengguo.orangemall.oms.vo.OmsMoneyInfoParam;
import link.chengguo.orangemall.oms.vo.OmsOrderDeliveryParam;
import link.chengguo.orangemall.oms.vo.OmsReceiverInfoParam;
import link.chengguo.orangemall.sys.entity.SysUser;
import link.chengguo.orangemall.util.UserUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表
 * </p>
 *
 * @author chengguo
 * @since 2019-04-19
 */
@Slf4j
@RestController
@Api(tags = "oms", description = "订单表管理")
@RequestMapping("/oms/OmsOrder")
public class OmsOrderController {
    @Resource
    private link.chengguo.orangemall.service.oms.IOmsOrderService IOmsOrderService;
    @Resource
    private IOmsOrderItemService orderItemService;

    @Resource
    private OmsOrderOperateHistoryMapper omsOrderOperateHistoryMapper;

    @SysLog(MODULE = "oms", REMARK = "根据条件查询所有订单表列表")
    @ApiOperation("根据条件查询所有订单表列表")
    @GetMapping(value = "/list")
    @PreAuthorize("hasAuthority('oms:OmsOrder:read')")
    public Object getOmsOrderByPage(OmsOrder entity,
                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {
            SysUser user= UserUtils.getCurrentMember();
            entity.setShopId(user.getShopId());
            String keyWord = null;
            if (entity.getGoodsName()!=null && !"".equals(entity.getGoodsName())){
                keyWord=entity.getGoodsName();
                entity.setGoodsName(null);
            }else{
                entity.setGoodsName(null);
            }
            Integer status=entity.getStatus();
            entity.setStatus(null);
            QueryWrapper queryWrapper=new QueryWrapper(entity);
            if (status!=null&&status!=0){
                switch (status){
                    case 1://待付款
                        queryWrapper.eq("status", OrderStatus.Default.getValue());
                        break;
                    case 2://待发货
                        queryWrapper.apply(
                                "(status ="+OrderStatus.WaitEnsure.getValue()+//待确认
                                        " or (status="+OrderStatus.Ensured.getValue()//已确认
                                        +" and (" +
                                        "verify_status ="+ VerifyStatus.WaitVerify.getValue()+//待核销
                                        " or express_status="+ ExpressStatus.ToDeliver.getValue()+//待发货
                                        " or (shipping_status <="+ ShippingStatus.ArrivedShop.getValue()//取货之前
                                        +" and shipping_status !=0))))");
                        break;
                    case 3://待收货
                        queryWrapper.apply(
                                "status=2 and (verify_status ="+VerifyStatus.Verifyed.getValue()+//已核销
                                        " or express_status="+ExpressStatus.Delivered.getValue()+//已发货
                                        " or shipping_status >"+ShippingStatus.ArrivedShop.getValue()//取货之后
                                        +")");
                        break;
                    case 4://已完成/待评价
                        queryWrapper.eq("status",OrderStatus.Finished.getValue());
//                        queryWrapper.eq("is_comment",0);
                        break;

                        //售后状态：1->退款申请，2->同意退款，3->拒绝退款，4->取消申请，5->退款退货申请，6->同意退款退货，7->拒绝退款退货，8->确认收货
                    case 5://申请退款
                        queryWrapper.apply(
                                "status=6 and (after_sale_status ="+ AfterSaleStatus.RefundApply.getValue()+//退款
                                        " or after_sale_status="+AfterSaleStatus.RefundGoodsApply.getValue()//退货
                                        +")");
                        break;
                    case 6://已退款
                        queryWrapper.apply(
                                "status=6 and (after_sale_status !="+AfterSaleStatus.RefundApply.getValue()+//退款
                                        " and after_sale_status !="+AfterSaleStatus.RefundGoodsApply.getValue()//退货
                                        +")");
                        break;
                    case 7://已关闭、已取消
                        queryWrapper.apply(
                                " (status ="+OrderStatus.Canceled.getValue()+//取消
                                        " or status="+OrderStatus.Closed.getValue()//关闭
                                        +")");
                        break;
                    default:
                        break;
                }
            }
            if (keyWord!=null){
                queryWrapper.apply("( order_sn like '%"+keyWord+"%' or receiver_phone like '%"+keyWord+"%' or receiver_name like '%"+keyWord+"%')");
            }

            // 如果为空，则查询非扫码购的所有订单
            if(entity.getSendType() ==null){
                queryWrapper.ne("send_type", SendType.CodeBuy.getValue());
            }
            if (entity.getStartTime()!=null && !"".equals(entity.getStartTime())){
                queryWrapper.ge("create_time",entity.getStartTime());
                queryWrapper.le("create_time",entity.getEndTime()+" 23:59:59");
            }
            queryWrapper.orderByDesc("create_time");
            IPage page=IOmsOrderService.page(new Page<>(pageNum, pageSize), queryWrapper);
            return new CommonResult().success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有订单表列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    /**
     * 获取店铺配送模式
     * @return
     */
    @ApiOperation("查询商家各分类订单数量")
    @PostMapping(value = "/getOrderNumberForShop")
    @ResponseBody
    public Object getOrderNumberForShop(@RequestParam("sendType") Integer sendType) {
        SysUser user= UserUtils.getCurrentMember();
        OmsOrder order=new OmsOrder();
        QueryWrapper queryWrapper=null;
        order.setShopId(user.getShopId());

        if (sendType!=null){
            order.setSendType(sendType);
        }

        //查询订单总数量
        queryWrapper=new QueryWrapper(order);
        int allCount=IOmsOrderService.count(queryWrapper);

        //查询待付款订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.eq("status",OrderStatus.Default.getValue());
        int waitPayCount=IOmsOrderService.count(queryWrapper);

        //查询待发货订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                "(status ="+OrderStatus.WaitEnsure.getValue()+//待确认
                        " or (status="+OrderStatus.Ensured.getValue()//已确认
                        +" and (" +
                        "verify_status ="+VerifyStatus.WaitVerify.getValue()+//待核销
                        " or express_status="+ExpressStatus.ToDeliver.getValue()+//待发货
                        " or (shipping_status <="+ShippingStatus.ArrivedShop.getValue()//取货之前
                        +" and shipping_status !=0))))");
        int waitSendCount=IOmsOrderService.count(queryWrapper);

        //查询待收货订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                "status=2 and (verify_status ="+VerifyStatus.Verifyed.getValue()+//已核销
                        " or express_status="+ExpressStatus.Delivered.getValue()+//已发货
                        " or shipping_status >"+ShippingStatus.ArrivedShop.getValue()//取货之后
                        +")");
        int waitReceiveCount=IOmsOrderService.count(queryWrapper);

        //查询待评价订单数量
        queryWrapper.eq("status",OrderStatus.Finished.getValue());
        queryWrapper.eq("is_comment",0);
        queryWrapper=new QueryWrapper(order);
        int waitCommentCount=IOmsOrderService.count(queryWrapper);

        //查询已完成订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.eq("status",OrderStatus.Finished.getValue());
        int finishCount=IOmsOrderService.count(queryWrapper);

        //查询查询申请退款订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                "status=6 and (after_sale_status ="+AfterSaleStatus.RefundApply.getValue()+//退款
                        " or after_sale_status="+AfterSaleStatus.RefundGoodsApply.getValue()//退货
                        +")");
        int refundApplyCount=IOmsOrderService.count(queryWrapper);

        //完成退款
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                "status=6 and (after_sale_status !="+AfterSaleStatus.RefundApply.getValue()+//退款
                        " and after_sale_status !="+AfterSaleStatus.RefundGoodsApply.getValue()//退货
                        +")");
        int refundFinishCount=IOmsOrderService.count(queryWrapper);

        //已关闭/已取消
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                " (status ="+OrderStatus.Canceled.getValue()+//取消
                        " or status="+OrderStatus.Closed.getValue()//关闭
                        +")");
        int closeCount=IOmsOrderService.count(queryWrapper);

        Map<String,Integer> map=new HashedMap();
        map.put("allCount",allCount);
        map.put("waitPayCount",waitPayCount);
        map.put("waitSendCount",waitSendCount);
        map.put("waitReceiveCount",waitReceiveCount);
        map.put("waitCommentCount",waitCommentCount);
        map.put("finishCount",finishCount);
        map.put("refundApplyCount",refundApplyCount);
        map.put("refundFinishCount",refundFinishCount);
        map.put("closeCount",closeCount);
        return new CommonResult().success(map);
    }


    @SysLog(MODULE = "oms", REMARK = "删除订单表")
    @ApiOperation("删除订单表")
    @GetMapping(value = "/delete/{id}")
    @PreAuthorize("hasAuthority('oms:OmsOrder:delete')")
    public Object deleteOmsOrder(@ApiParam("订单表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("订单表id");
            }
            if (IOmsOrderService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除订单表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "给订单表分配订单表")
    @ApiOperation("查询订单表明细")
    @GetMapping(value = "/{id}")
    public Object getOmsOrderById(@ApiParam("订单表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("订单表id");
            }
            OmsOrder coupon = IOmsOrderService.getById(id);
            coupon.setOrderItemList(orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", coupon.getId())));
            coupon.setHistoryList(omsOrderOperateHistoryMapper.selectList(new QueryWrapper<OmsOrderOperateHistory>().eq("order_id", coupon.getId())));
            return new CommonResult().success(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询订单表明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }

    @ApiOperation(value = "批量删除订单表")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @ResponseBody
    @SysLog(MODULE = "pms", REMARK = "批量删除订单表")
    @PreAuthorize("hasAuthority('oms:OmsOrder:delete')")
    public Object deleteBatch(@RequestParam("ids") List<Long> ids) {
        boolean count = IOmsOrderService.removeByIds(ids);
        if (count) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "oms", REMARK = "批量发货")
    @ApiOperation("批量发货")
    @RequestMapping(value = "/update/delivery", method = RequestMethod.POST)
    @ResponseBody
    public Object delivery(@RequestBody List<OmsOrderDeliveryParam> deliveryParamList) {
        int count = IOmsOrderService.delivery(deliveryParamList);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "批量发货")
    @ApiOperation("批量发货")
    @RequestMapping(value = "/delivery", method = RequestMethod.POST)
    @ResponseBody
    public Object singleDelivery(@RequestBody OmsOrderDeliveryParam deliveryParamList) {
        int count = IOmsOrderService.singleDelivery(deliveryParamList);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "批量关闭订单")
    @ApiOperation("批量关闭订单")
    @RequestMapping(value = "/update/close", method = RequestMethod.POST)
    @ResponseBody
    public Object close(@RequestParam("ids") List<Long> ids, @RequestParam String note) {
        int count = IOmsOrderService.close(ids, note);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "修改收货人信息")
    @ApiOperation("修改收货人信息")
    @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) {
        int count = IOmsOrderService.updateReceiverInfo(receiverInfoParam);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "修改订单费用信息")
    @ApiOperation("修改订单费用信息")
    @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
        int count = IOmsOrderService.updateMoneyInfo(moneyInfoParam);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "备注订单")
    @ApiOperation("备注订单")
    @RequestMapping(value = "/update/note", method = RequestMethod.POST)
    @ResponseBody
    public Object updateNote(@RequestParam("id") Long id,
                             @RequestParam("note") String note,
                             @RequestParam("status") Integer status) {
        int count = IOmsOrderService.updateNote(id, note, status);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "oms", REMARK = "商家接单")
    @ApiOperation("商家接单")
    @RequestMapping(value = "/update/ensure", method = RequestMethod.POST)
    @ResponseBody
    public Object ensureOrder(@RequestParam("orderId") Long orderId,@RequestParam("sendType")Integer sendType) {
        if (sendType==null){
            return new CommonResult().failed("配送方式不能为空");
        }
        if (orderId==null){
            return new CommonResult().failed("订单ID不能为空");
        }
        int count = IOmsOrderService.ensureOrder(orderId,sendType);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "商家拒绝接单")
    @ApiOperation("商家拒绝接单")
    @RequestMapping(value = "/update/refuse", method = RequestMethod.POST)
    @ResponseBody
    public Object refuseOrder(@RequestParam("orderId") Long orderId,@RequestParam("sendType")Integer sendType) {
        if (sendType==null){
            return new CommonResult().failed("配送方式不能为空");
        }
        if (orderId==null){
            return new CommonResult().failed("订单ID不能为空");
        }
        int count = IOmsOrderService.refuseOrder(orderId,sendType);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "oms", REMARK = "待上门取货")
    @ApiOperation("待上门取货")
    @RequestMapping(value = "/update/waitGet", method = RequestMethod.POST)
    @ResponseBody
    public Object waitGet(@RequestParam("orderId") Long orderId,@RequestParam("sendType")Integer sendType) {
        if (orderId==null){
            return new CommonResult().failed("订单ID不能为空");
        }
        int count = IOmsOrderService.updateWaitGet(orderId,sendType);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }


    @ApiOperation(value = "查询订单列表")
    @GetMapping(value = "/order/list")
    public Object orderList(OmsOrder order,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {

        IPage<OmsOrder> page = null;
        if (order.getStatus() != null && order.getStatus() == 0) {
            page = IOmsOrderService.page(new Page<OmsOrder>(pageNum, pageSize), new QueryWrapper<OmsOrder>().orderByDesc("create_time"));
        } else {
            page = IOmsOrderService.page(new Page<OmsOrder>(pageNum, pageSize), new QueryWrapper<>(order).orderByDesc("create_time"));

        }
        for (OmsOrder omsOrder : page.getRecords()) {
            List<OmsOrderItem> itemList = orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", omsOrder.getId()).eq("type", AllEnum.OrderItemType.GOODS.code()));
            omsOrder.setOrderItemList(itemList);
        }
        return new CommonResult().success(page);
    }

    @SysLog(MODULE = "oms", REMARK = "核销订单")
    @ApiOperation("核销订单")
    @RequestMapping(value = "/update/verify", method = RequestMethod.POST)
    @ResponseBody
    public Object updateNote(@RequestParam("orderId") Long orderId) {
        int count = IOmsOrderService.orderVerify(orderId);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

}
